﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
using SchoolLibrary;
using System.Collections;
using SchoolLibrary.DataBase.DAO;
using SchoolLibrary.Entity;
using SchoolLibrary.Desktop.Report;
using SchoolLibrary.Desktop.Guide;
using SchoolLibrary.Entity.Person;
using SchoolLibrary.DataBase.Connect;
using SchoolLibrary.Desktop.Common.Dialog;
using SchoolLibrary.Desktop.Report.Dialog;

namespace SchoolLibrary.Desktop
{
    public partial class MainForm : Form
    {
        private const string ID_COLUMN_NAME = "id";
        private const string ROW_NUM_COLUMN_NAME = "№";
        private const string BOOK_COLUMN_NAME = "Книга";
        private const string PUPIL_COLUMN_NAME = "Ученик";
        private const string ISSUE_DATE_COLUMN_NAME = "Дата выдачи";
        private const string DAY_AMOUNT_COLUMN_NAME = "Кол-во дней";
        private const string BAIL_COLUMN_NAME = "Сумма залога";
        private const string RETURN_DATE_COLUMN_NAME = "Дата возврата";
        private const int DEFAULT_COLUMN_SIZE = 100;

        private DataTable table;
        private List<RegistryJournal> data = new List<RegistryJournal>();

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            InitializeTable();
            this.dataGridView.DataSource = table;
            updateData();
           // new SqliteConnection().Open();
        }

        private void updateData()
        {
            clear();
            List<RegistryJournal> records = RegistryJournalDAO.getInstance().findAll();
            foreach (RegistryJournal record in records)
            {
                AddRegisterJournalRecord(record);
            }
            this.dataGridView.ClearSelection();
        }

        private void clear() 
        {
            table.Rows.Clear();
            data.Clear();
        }

        private void InitializeTable()
        {
            table = new DataTable();
            table.Columns.Add(ID_COLUMN_NAME);
            table.Columns.Add(ROW_NUM_COLUMN_NAME);
            table.Columns.Add(BOOK_COLUMN_NAME);
            table.Columns.Add(PUPIL_COLUMN_NAME);
            table.Columns.Add(ISSUE_DATE_COLUMN_NAME);
            table.Columns.Add(DAY_AMOUNT_COLUMN_NAME);
            table.Columns.Add(BAIL_COLUMN_NAME);
            table.Columns.Add(RETURN_DATE_COLUMN_NAME);

            dataGridView.DataSource = table;
            dataGridView.Columns[ID_COLUMN_NAME].Visible = false;
            dataGridView.Columns[ROW_NUM_COLUMN_NAME].Width = DEFAULT_COLUMN_SIZE / 3;
            dataGridView.Columns[BOOK_COLUMN_NAME].Width = (int)(DEFAULT_COLUMN_SIZE * 1.5);

            foreach (DataGridViewColumn column in dataGridView.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
        }

        private void AddRegisterJournalRecord(RegistryJournal record)
        {
            data.Add(record);
            DataRow row = table.NewRow();
            table.Rows.Add(row);
            row[ID_COLUMN_NAME] = record.Id;
            row[ROW_NUM_COLUMN_NAME] = data.IndexOf(record) + 1;
            row[BOOK_COLUMN_NAME] = record.Book.Name;
            row[PUPIL_COLUMN_NAME] = record.Pupil.AbbreviatedName;
            row[ISSUE_DATE_COLUMN_NAME] = String.Format("{0:dd.MM.yyyy}", record.IssueDate);
            row[DAY_AMOUNT_COLUMN_NAME] = record.DayAmount;
            row[BAIL_COLUMN_NAME] = record.Bail;
            if (record.ReturnDate.Ticks > 0)
            {
                row[RETURN_DATE_COLUMN_NAME] = String.Format("{0:dd.MM.yyyy}", record.ReturnDate);
                dataGridView.Rows[dataGridView.Rows.Count - 1].DefaultCellStyle.BackColor = Color.LightGray;
            }

        }

        private void bookGuideMenuItem_Click(object sender, EventArgs e)
        {
            BookGuide guide = new BookGuide();
            guide.initData();
            guide.ShowDialog();
        }

        private void returnBook_Click(object sender, EventArgs e)
        {
            foreach (RegistryJournal record in getSelectedRecords())
            {
                RegistryJournalDAO.getInstance().updateReturnDate(record.Id, DateTime.Now); 
            } 
            updateData();
        }

        private List<RegistryJournal> getSelectedRecords()
        {
            List<RegistryJournal> journalRecords = new List<RegistryJournal>();
            foreach (DataGridViewRow selectedRow in dataGridView.SelectedRows)
            {
               int selectedRowIndex = dataGridView.Rows.IndexOf(selectedRow);
               journalRecords.Add(data[selectedRowIndex]);

            }
            return journalRecords;
        }

        private void dataGridView_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            bool isValid = true;
            List<RegistryJournal> journalRecords = getSelectedRecords();
            foreach (RegistryJournal record in journalRecords)
            {
                isValid = isValid && record.ReturnDate.Ticks <= 0;
            }
            this.returnBook.Enabled = isValid;
        }

        private void giveBook_Click(object sender, EventArgs e)
        {
            GiveBookForm form = new GiveBookForm();
            form.ShowDialog();
            updateData();
        }

        private void pupilGuideMenuItem_Click(object sender, EventArgs e)
        {
            List<Pupil> pupils = PupilDAO.getInstance().findAll();
            PupilGuide guide = new PupilGuide();
            guide.initData();
            guide.ShowDialog();
        }

        private void bookReportMenuItem_Click(object sender, EventArgs e)
        {
            List<Book> books = BookDAO.getInstance().findAll();
            BookReport bookReport = new BookReport(books);
            bookReport.ShowDialog();
        }

        private void classGuideMenuItem_Click(object sender, EventArgs e)
        {
            ClassGuideForm form = new ClassGuideForm();
            form.initData();
            form.ShowDialog();
        }

        private void classLeaderGuildeMenuItem_Click(object sender, EventArgs e)
        {
            ClassLeaderGuideForm form = new ClassLeaderGuideForm();
            form.initData();
            form.ShowDialog();
        }

        private void writersMenuItem_Click(object sender, EventArgs e)
        {
            WriterGuideForm form = new WriterGuideForm();
            form.initData();
            form.ShowDialog();
        }

        private void bookNameSearchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InputDialog dialog = new InputDialog();
            dialog.ShowDialog();
            string name = dialog.Value;
            if (name != null)
            {
                List<Book> books = BookDAO.getInstance().findByName(name);
                BookReport bookReport = new BookReport(books);
                bookReport.ShowDialog();
            }
        }

        private void searchPupilsByClassToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ClassSelectDialog dialog = new ClassSelectDialog();
            dialog.ShowDialog();
            Class selectedClass = dialog.SelectedClass;
            if (selectedClass != null)
            {
                List<Pupil> pupils = PupilDAO.getInstance().findBookHoldersByClass(selectedClass);                
            }
        }   

    }

}

